package cnooc.dataAnalysis.controller;


import cn.hutool.core.collection.CollUtil;
import cnooc.common.core.controller.BaseController;
import cnooc.common.core.domain.AjaxResult;
import cnooc.common.core.page.TableDataInfo;
import cnooc.dataAnalysis.domain.AnalysisParam;
import cnooc.dataAnalysis.service.HistoryService;
import cnooc.energy.domain.DeviceDataLocation;
import cnooc.energy.domain.Equipment;
import cnooc.energy.service.IDeviceDataLocationService;
import cnooc.energy.service.IEquipmentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 历史数据查询Controller
 *
 * @author lambda
 * @date 2023-11-28
 */
@RestController
@RequestMapping("/dataAnalysis/history")
public class HistoryController extends BaseController {
    @Resource
    HistoryService historyService;
    @Resource
    IDeviceDataLocationService deviceDataLocationService;
    @Resource
    IEquipmentService equipmentService;

    @GetMapping("/queryHistoricalData")
    public AjaxResult queryHistoricalData(AnalysisParam param) {
        Equipment equipment = equipmentService.selectEquipmentById(param.getDeviceId());
        Map<String, Object> result;
        TableDataInfo rows;
        List<DeviceDataLocation> deviceDataLocations = param.getLocationId() != null ?
                CollUtil.newArrayList(deviceDataLocationService.selectDeviceDataLocationById(param.getLocationId())) :
                deviceDataLocationService.selectLocationByDeviceId(param.getDeviceId(), null);

        int limit = param.getPageSize();
        int offset = param.getPageSize() * (param.getPageNum()-1);

        rows = getDataTable(historyService.queryHistoricalData(param.getDatetimeRange(), equipment, deviceDataLocations, limit, offset));

        result = historyService.resultPackaging(equipment, CollUtil.newArrayList(deviceDataLocations), rows.getRows());
        rows.setRows((List<?>) result.get("rows"));
        rows.setTotal(historyService.count(equipment.getTableName(), deviceDataLocations.get(0).getLocation(), param.getDatetimeRange()));
        result.put("rows", rows);
        return AjaxResult.success(result);


    }

}
